<template>
	<view style="width:100vw;height: 100vh;overflow: hidden;">

		<view class="icon" :style="{'paddingTop':statusTop+'px',height:statusHeight+'px'}" style="">
			<u-icon name="arrow-left" size="20" @click='backPage'></u-icon>
			<view v-if="floorTileStatus" style="display: flex;align-items: center;">
				<image style="margin-right: 5rpx;" @click='drawChange'
					src="https://renovationcdn.jiachuangnet.com/cad/draw.png">
				</image>
				<image style="margin-right: 5rpx;" src="https://renovationcdn.jiachuangnet.com/cad/save.png"
					@click='printLineInfo'></image>
				<image src="https://renovationcdn.jiachuangnet.com/cad/back.png" @click="backFloorTile"></image> 
				<!-- <view style="margin-left: 20rpx;font-size: 24rpx;"  @click='toMaterimal'>选择其他材料</view> -->
			</view>
			<view v-else>
				<!-- <image style="margin-right: 5rpx;" src="https://renovationcdn.jiachuangnet.com/cad/save.png"
				   v-if="brandPartyId ==1 && isFirst == 1 "
					@click='printLineInfo'></image> -->
				<image @click='bleShow=true' src="https://renovationcdn.jiachuangnet.com/cad/ble.png"></image>
				<image src="https://renovationcdn.jiachuangnet.com/cad/back.png" @click="undoLine"></image>
				<image @click="toggleMode" v-if="mode == 'translate'"
					src="https://renovationcdn.jiachuangnet.com/cad/trans.png">
				</image>
				<image @click="toggleMode" v-else src="https://renovationcdn.jiachuangnet.com/cad/line.png">
				</image>
				<image src="https://renovationcdn.jiachuangnet.com/cad/delete.png" @click="deleteSelectedLine"></image>
				<image src="https://renovationcdn.jiachuangnet.com/cad/copy.png" @click="copySelectedLine"></image>
				<image src="https://renovationcdn.jiachuangnet.com/cad/clear.png" @click="clearCanvas"></image>
			</view>
		</view>
		<canvas canvas-id="firstCanvas" id="firstCanvas" ref="canvas" :style="{top:top+'px',left:left + 'px'}"
			style="width:3000px;height: 3000px;z-index:100;" @touchstart="handleMouseDown"
			@touchmove.stop="handleMouseMove" @touchend="handleMouseUp" @touchcancel="handleMouseLeave"></canvas>
		<!-- <view v-if="floorTileStatus"
			style="position: fixed;z-index:10000000000;top:15%;left:20rpx;padding:30rpx 20rpx;background: white;border-radius: 67rpx;">
			<view>
				<view
					:style="{'color':color,'fontSize':'32rpx','fontWeight':'700','textAlign':'center','marginTop':'10rpx'}">
					{{wallboardNum}}
				</view>
				<view style="text-align: center;">护墙</view>
			</view>
			<view @click="lengthShow = true">
				<view
					:style="{'color':color,'fontSize':'32rpx','fontWeight':'700','textAlign':'center','marginTop':'10rpx'}">
					{{carbonCrystalPlateNum}}
				</view>
				<view style="text-align: center;">碳晶</view>
			</view>
			<view style="margin-top: 20rpx;" @click="storkeReacMap">
				<view
					:style="{'color':color,'fontSize':'32rpx','fontWeight':'700','textAlign':'center','marginTop':'10rpx'}">
					{{floorTileNum}}
				</view>
				<view style="text-align: center;">地砖</view>
			</view>
		</view> -->
		<!-- 		<view
			style="position: fixed;z-index:10000000000;top:15%;right:20rpx;padding:30rpx 20rpx;background: white;border-radius: 67rpx;">
			<view @click='bleShow=true'>
				<view style="display: flex;justify-content: center;">
					<image src="https://renovationcdn.jiachuangnet.com/cad/ble.png" style="width: 50rpx;height: 50rpx;">
					</image>
				</view>
				<view>蓝牙</view>
			</view>
			<view @click="undoLine" style="margin-top:20px">
				<view style="display: flex;justify-content: center;">
					<image src="https://renovationcdn.jiachuangnet.com/cad/back.png"
						style="width: 50rpx;height: 50rpx;">
					</image>
				</view>
				<view>撤回</view>
			</view>
			<view style="margin-top:20px" @click="toggleMode">
				<view style="display: flex;justify-content: center;">
					<image v-if="mode == 'translate'" src="https://renovationcdn.jiachuangnet.com/cad/trans.png"
						style="width: 50rpx;height: 50rpx;">
					</image>
					<image v-else src="https://renovationcdn.jiachuangnet.com/cad/line.png"
						style="width: 50rpx;height: 50rpx;">
					</image>
				</view>

				<view>{{ mode === 'translate' ? '旋转' : '平移' }}</view>
			</view>
			<view @click="deleteSelectedLine" style="margin-top:20px">
				<view style="display: flex;justify-content: center;">
					<image src="https://renovationcdn.jiachuangnet.com/cad/delete.png"
						style="width: 50rpx;height: 50rpx;">
					</image>
				</view>

				<view>删除</view>
			</view>
			<view @click="copySelectedLine" style="margin-top:20px">
				<view style="display: flex;justify-content: center;">
					<image src="https://renovationcdn.jiachuangnet.com/cad/copy.png"
						style="width: 50rpx;height: 50rpx;">
				</view>

				</image>
				<view>复制</view>
			</view>
			<view style="margin:20rpx 0" @click='printLineInfo'>
				<view style="display: flex;justify-content: center;">
					<image src="https://renovationcdn.jiachuangnet.com/cad/save.png"
						style="width: 50rpx;height: 50rpx;">
					</image>
				</view>

				<view>保存</view>
			</view>
			<view @click="clearCanvas">
				<view style="display: flex;justify-content: center;">
					<image src="https://renovationcdn.jiachuangnet.com/cad/clear.png"
						style="width: 50rpx;height: 50rpx;">
					</image>
				</view>

				<view>清空</view>
			</view>
		</view> -->
		<!-- <view v-if="floorTileStatus" class="tabbar"
			style="padding: 20rpx 40rpx;width:calc(100% - 80rpx);padding-bottom:80rpx;background-color: white;">
			<view style="display:flex;justify-content: space-between;">
				<text>
					面积：<text :style="{'color':color}">{{areaData}}</text>
				</text>
				<text style="margin: 0 10rpx;">
					护墙：<text :style="{'color':color}">{{wallboardNum}}</text>
				</text>
				<text @click="lengthShow = true" style="margin-right: 10rpx;">
					碳晶：<text :style="{'color':color}">{{carbonCrystalPlateNum}}</text>
				</text>
				<text @click="storkeReacMap">
					地砖：<text :style="{'color':color}">{{floorTileNum}}</text>
				</text>

			</view>
			<view style="width: 500rpx;margin:0 auto;margin-top: 40rpx;" v-if="brandPartyId == 2 && isFirst ==1">
				<u-button :color='color' shape='circle' @click='computationalMaterials'>材料预览</u-button>
			</view>
			<view style="width: 500rpx;margin:0 auto;margin-top: 40rpx;" v-if="brandPartyId == 1 && isFirst == 2">
				<u-button :color='color' shape='circle' @click='outDoor'>下一步，室外材料</u-button>
			</view>
		</view> -->

		<view class="tabbar" v-if="!floorTileStatus">
			<view
				style="display: flex;align-items: center;background: #c7e9ea;padding:0 20rpx;border-top-left-radius: 20rpx;border-top-right-radius: 20rpx;">
				<view style="width: 80px;font-size: 24rpx;">缩放:</view>
				<view style="width: calc(100% - 80rpx);">
					<u-slider style="margin:20rpx 0;" v-model="scale" :step='0.1' :max='1' :blockColo='color'
						inactiveColor='#eee' :activeColor='color' :min='0.01'></u-slider>
				</view>
			</view>
			<view style="padding:20rpx;background-color: white;" :style="{'paddingBottom':safeBottom+'px'}">
				<view style="display: flex;justify-content: space-between;border-radius: 20rpx;">
					<view style="
					 	 width: 47%;
						 height: 88rpx;
					 	background: #F5FFFF;
					 	border-radius: 20rpx;
					 	border: 1px solid #13989A;display: flex;align-items: center;">
						<u-input customStyle='font-size:26rpx;font-weight:700;height:70rpx;width: calc(100% - 100rpx);'
							v-model="lineLength" placeholder="请输入线段长度(CM)" type="number"></u-input>
						<view @click='changeLineTypeShow = true'
							style="width: 90rpx;font-size: 24rpx;display: flex;align-items: center;">
							<view>{{lineType === 'horizontal'? '水平':'垂直'}}</view>
							<u-icon name="arrow-down-fill" color='#C9C9C9' size="14"></u-icon>
						</view>
					</view>
					<view style="width: 47%;display: flex;text-align: center;line-height: 88rpx;">
						<view style="width:50%;border-top-left-radius:20rpx;border-bottom-left-radius:20rpx;color:white"
							:style="{'background':color,}" @click="addLine">
							增加
						</view>
						<view
							style="width:50%;border-top-right-radius:20rpx;border-bottom-right-radius:20rpx;background-color: #d0eaeb"
							@click="storkeReacMap" :style="{'color':color}">
							计算铝塑板
						</view>
						<!-- <u-button custom-style='border-top-left-radius:30rpx;border-bottom-left-radius:30rpx' :color='color' @click="addLine">增加</u-button>
							<u-button custom-style='border-top-right-radius:30rpx;border-bottom-right-radius:30rpx;' :style='{"color":color}' color='' @click="storkeReacMap">计算地砖</u-button> -->
					</view>
				</view>
			</view>
			<!-- <view style="width:100%;display: flex;justify-content: space-between;align-items: center;">
				<view style="font-weight: blod;font-size: 32rpx;color:#1e272e">类型：</view>
				<view style="display: flex;justify-content: flex-end;">
					<u-radio-group size="24" v-model="lineType" placement="row">
						<u-radio :customStyle="{marginLeft: '8px'}" :activeColor="color" name='horizontal'
							key='horizontal' label="水平"></u-radio>
						<u-radio :customStyle="{marginLeft: '8px'}" :activeColor="color" name='vertical' key='vertical'
							label="垂直"></u-radio>
					</u-radio-group>
				</view>
			</view> -->
			<!-- 	<view style="
			margin:30rpx 0;
			background: #F5FFFF;
			border-radius: 20rpx;
			border: 1px solid #13989A;">
				<u-input customStyle='height:70rpx;font-size:26rpx;font-weight:700' style="width: calc(100% - 100rpx);"
					v-model="lineLength" type="number"></u-input>
			</view>
			<u-button custom-style='height: 90rpx;border-radius:30rpx' :color='color' @click="addLine">增加</u-button>
			<u-button @click="storkeReacMap">下一步，计算地砖</u-button> -->
		</view>
		<u-popup :show="bleShow" mode="center" bgColor='transparent'>
			<view style="width:80vw;">
				<ble @value='getValue' @close='getClose' @notifyClose='getNotifyClose' />
			</view>
		</u-popup>
		<u-popup :show="RBSHOW" @close='lengthClose' mode="bottom">
			<view style='padding:20rpx;width:calc(100% - 40rpx);padding-bottom:100rpx'>
				<view style="padding: 20rpx;text-align: center;">
					材料选择</view>
				<scroll-view @scroll="scroll" scroll-y="true" style="height: 600rpx;">
					<view v-for="(v,i) in RBLIST" :key="i"
						style="padding:20rpx 0;text-align:center;border-bottom:1rpx solid #eee;display:flex;align-items: center;justify-content: space-between;">
						<text style="width: 50%;">{{v.firstMaterialName}}</text>
						<text style="width: 20%;">{{v.firstMaterialPrice}}</text>
						<view style="width: 30%;">
							<uni-number-box v-model="v.count"></uni-number-box>
						</view>
					</view>
				</scroll-view>
				<view style="margin-top:50rpx;"><u-button :color='color' shape='circle'
						@click='createOrder'>创建订单</u-button></view>
			</view>
		</u-popup>
		<u-popup :show="lengthShow" mode='center' @close="lengthClose">
			<view style='padding:20rpx'>
				<view style="font-size: 24rpx;">
					<text style="color:red;margin:0 20rpx">*</text>请输入碳晶板的长度（厘米）
				</view>
				<view style="
				margin:30rpx 0;
				background: #F5FFFF;
				border-radius: 20rpx;
				border: 1px solid #13989A;">
					<u-input customStyle='height:50rpx;font-size:26rpx;font-weight:700'
						style="width: calc(100% - 100rpx);" v-model="carbonCrystalPlateLength" type="number"></u-input>
				</view>
				<u-button size='small' :color='color' @click='lengthClose'>保存</u-button>
			</view>
		</u-popup>
		<u-action-sheet cancelText="取消" :closeOnClickOverlay="true" :closeOnClickAction="true" :actions="lineTypeList"
			@select='lineTypeConfirm' @close='lineTypeClose' title="请选择线段方向"
			:show="changeLineTypeShow"></u-action-sheet>
		<!-- <u-picker :confirmColor='color' :show="changeLineTypeShow" @close='lineTypeClose' @cancel='lineTypeClose' @confirm='lineTypeConfirm' :columns="columns"></u-picker> -->

	</view>
</template>
<script>
	let app = getApp();
	import ble from '../ble/index.vue'
	import Decimal from 'decimal.js'
	export default {
		components: {
			ble
		},
		data() {
			return {
				brandPartyId: null,
				isFirst: null,
				lineTypeList: [{
						'name': '水平线段',
						'value': 'horizontal'
					},
					{
						'name': '垂直线段',
						'value': 'vertical'
					}

				],
				bleShow: false,
				statusHeight: 40,
				floorTileStatus: false,
				carbonCrystalPlateNum: 0,
				scale: 1,
				lengthShow: false,
				floorTileNum: 0,
				color: app.globalData.defaultColor,
				safeBottom: app.globalData.safeBottom,
				lineType: 'horizontal', // 'horizontal' 或 'vertical'
				lineLength: null,
				lines: [],
				statusTop: app.globalData.statusTop || 0,
				draggingLine: null,
				draggingOffsetX: 0,
				draggingOffsetY: 0,
				isDrawing: false,
				snapDistance: 10, // 吸附距离
				canvas: null,
				ctx: null,
				lineWidth: 1,
				type: 'black',
				lineArry: [],
				moveRect: null,
				lineColor: '#000000',
				downRect: null,
				canvasWidth: 0,
				selectedLine: null, // 新增：选中的直线
				canvasHeight: 0,
				showAnnotations: true, // 新增：是否显示标注
				changeLineTypeShow: false,
				startX: 0,
				startY: 0,
				left: 0,
				top: 0,
				offsetX: 0,
				offsetY: 0,
				rotatingLine: null, // 正在旋转的直线
				rotatingPoint: null, // 旋转的固定点
				mode: 'translate', // 新增：当前模式，'translate' 或 'rotate'
				wallboardNum: 0, //护墙板数量
				wallboardLength: 0, // 护墙板米数
				carbonCrystalPlateLength: 0, //碳晶板米数
				carbonCrystalPlateNum: 0, //碳晶板数量
				gridArr: [],
				gridSize: 80,
				coverShow: false,
				areaData: 0,
				id: null,
				isFirst: 1, //2为复尺 1为初尺
				storeType: 1, //1普通店 2旗舰店
				delGrid: [], //被删除的地砖
				RBLIST: [],
				RBSHOW: false,
				old: {
					scrollTop: 0
				},
				boxBorder: {
					minStartX: 0,
					maxStartY: 0,
					minEndX: 0,
					maxEndY: 0
				}
			}
		},



		onLoad(option) {
			if (option) {
				this.id = option.id;
				this.stroeType = option.stroeType;
				this.isFirst = option.isFirst
				this.brandPartyId = option.brandPartyId //品牌方id 1 零食很忙 2 罗比

			}
		},
		onShow() {

			this.ctx = uni.createCanvasContext('firstCanvas', this);
			const query = uni.createSelectorQuery();

			// #ifdef mp-weixin
			const menuButton = uni.getMenuButtonBoundingClientRect();
			this.statusHeight = menuButton.height;
			// #endif
			query.select('#firstCanvas').fields({
				size: true
			}, (res) => {
				this.canvasWidth = res.width;
				this.canvasHeight = res.height;
				this.redrawCanvas();

			}).exec();
		},
		watch: {
			'scale': {
				handler(newVal) {
					this.ctx.scale(newVal, newVal);
					if (this.floorTileStatus) {
						this.storkeReacMap();
					}
					this.redrawCanvas();
				}
			},
			'gridArr': {
				handler(newVal) {
					if (newVal) {
						this.ctx.strokeStyle = '#c9c9c9';
						newVal.map(el => {
							if (this.brandPartyId == 1) {
								this.ctx.strokeRect(el.x, el.y, 122, 300);

							} else if (this.brandPartyId == 2) {
								this.ctx.strokeRect(el.x, el.y, 120, 60);
							}
						})
						this.ctx.draw(true);
						this.floorTileNum = newVal.length;
					}
					this.ctx.strokeStyle = 'black';
					if (this.brandPartyId == 1) {
						this.areaData = Decimal(0.64).mul(Decimal(newVal.length)).toNumber();

					} else if (this.brandPartyId == 2) {
						this.areaData = Decimal(0.72).mul(Decimal(newVal.length)).toNumber();
					}
				},
				deep: true,
			},
			'carbonCrystalPlateLength': {
				handler(newVal) {
					if (this.carbonCrystalPlateLength && this.wallboardLength != 0 && this.wallboardLength >= this
						.carbonCrystalPlateLength) {
						this.wallboardNum = Math.ceil(Decimal(this.wallboardLength).sub(Decimal(newVal)).div(122)
							.toNumber());
						this.carbonCrystalPlateNum = Math.ceil(Decimal(newVal).div(Decimal(122)).toNumber());
					}
				}
			},
			'lines': {
				handler(newVal, oldVal) {
					let minEndX = 0;
					let maxEndX = 0;
					let minEndY = 0;
					let maxEndY = 0;
					let length = 0;
					newVal.map(el => {
						if (el.type == "horizontal") {
							el.length = Decimal(el.endX).sub(Decimal(el.startX)).toNumber();
						} else {
							el.length = Decimal(el.endY).sub(Decimal(el.startY)).toNumber();
						}
						length += el.length;
					})
					this.wallboardLength = length;
					//计算地砖 需要保证以原点(100,100)计算
					const endXValues = newVal.map(item => item.endX);
					const startXValues = newVal.map(item => item.startX);
					minEndX = Math.min(...startXValues); //x轴的起点
					maxEndX = Decimal(Math.max(...endXValues)).sub(Decimal(minEndX)).toNumber(); //X轴的终点
					const endYValues = newVal.map(item => item.endY);
					const startYValues = newVal.map(item => item.startY);
					minEndY = Math.min(...startYValues);
					maxEndY = Decimal(Math.max(...endYValues)).sub(Decimal(minEndY)).toNumber();
					this.boxBorder.minStartX = minEndX;
					this.boxBorder.maxStartX = maxEndX;
					this.boxBorder.minEndX = minEndY;
					this.boxBorder.maxEndY = maxEndY;
					this.wallboardNum = Math.ceil(Decimal(length).div(Decimal(122)).toNumber());
				},
				deep: true
			}
		},
		methods: {
			scroll: function(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
			polygonArea() {
				let area = 0;
				let vertices = []
				this.lines.map(el => {
					vertices.push([Decimal(el.startX).sub(Decimal(100)).div(Decimal(100)).toNumber(), Decimal(el
						.startY).sub(Decimal(100)).div(Decimal(100)).toNumber()])
				})
				// vertices.push([Decimal(this.lines[0].startX).sub(Decimal(100)).div(Decimal(100)).toNumber(),Decimal(this.lines[0].startY).sub(Decimal(100)).div(Decimal(100)).toNumber()])
				const n = vertices.length;

				if (n < 3) {
					return 0; // 无法构成多边形，返回0
				}
				for (let i = 0; i < n; i++) {
					const j = (i + 1) % n; // 下一个顶点
					const [x1, y1] = vertices[i];
					const [x2, y2] = vertices[j];
					area += (x1 * y2) - (x2 * y1); // 通过叉乘计算每个三角形的面积
				}
				this.areaData = Math.abs(area) / 2; // 因为向量有负值，所以最终的面积可能为负数，取绝对值
			},
			backFloorTile() {
				if (this.delGrid.length > 0) {
					this.gridArr.push(this.delGrid[this.delGrid.length - 1]);
					this.delGrid.pop();
					this.redrawCanvas();
				}
			},
			lengthClose() {
				this.lengthShow = false;
				this.RBSHOW = false;
				this.RBLIST = [];
			},
			lineTypeClose() {
				this.changeLineTypeShow = false;
			},
			lineTypeConfirm(e) {
				this.lineType = e.value
				this.lineTypeClose();
			},
			getClose(e) {
				if (e) {
					this.bleShow = false;
				}
			},
			outDoor() {
				uni.navigateTo({
					url: '/pages/newCad/index?id=' + this.id + '&storeType=' + this.storeType
				})
			},
			storkeReacMap() {
				if (this.lines.length == 0) {
					uni.$u.toast('请绘制CAD!');
					return;
				};
				this.floorTileStatus = true;
				this.floorTileNum = 0;
				this.gridArr = [];
				this.scale = 1;
				// this.ctx.strokeStyle = '#ccc';

				this.ctx.lineWidth = 1;

				let cols, rows = 0;
				if (this.brandPartyId == 1) {
					cols = Math.ceil(this.boxBorder.maxStartX / 122);
					rows = Math.ceil(this.boxBorder.maxEndY / 300);
				} else if (this.brandPartyId == 2) {
					cols = Math.ceil(this.boxBorder.maxStartX / 120);
					rows = Math.ceil(this.boxBorder.maxEndY / 60);
				}
				for (let i = 0; i < cols; i++) {
					for (let j = 0; j < rows; j++) {
						this.floorTileNum = (j + 1) * (i + 1);
						if (this.brandPartyId == 1) {
							this.gridArr.push({
								'x': this.boxBorder.minStartX + i *122,
								'y': this.boxBorder.minEndX + j * 300
							});
						} else if (this.brandPartyId == 2) {
							this.gridArr.push({
								'x': this.boxBorder.minStartX + i * 120,
								'y': this.boxBorder.minEndX + j * 60
							});
						}

					}
				}




			},
			getNotifyClose(e) {
				if (e) {
					this.bleShow = false;
				}
			},
			getValue(e) {
				this.lineLength = Decimal(e.slice(0, -1)).mul(Decimal(100)).toNumber();
			},
			backPage() {
			 uni.navigateTo({
			 	url:'/packageA/pages/panelCad/index'
			 })
			},
			calculatePolygonArea(vertices) {
				let sum1 = 0;
				let sum2 = 0;

				for (let i = 0; i < vertices.length; i++) {
					const j = (i + 1) % vertices.length; // 确保最后一个顶点连接到第一个顶点
					sum1 += vertices[i].x * vertices[j].y;
					sum2 += vertices[j].x * vertices[i].y;
				}


				const area = Math.abs(sum1 - sum2) / 2.0;
				return area;
			},


			toggleMode() {
				if (this.floorTileStatus) {
					uni.$u.toast('正在计算地砖，不可操作!');
					return;
				}
				this.mode = this.mode === 'translate' ? 'rotate' : 'translate';
			},
			drawChange() {
				this.floorTileStatus = false;
				this.gridArr = [];
				this.redrawCanvas();
			},
			deleteSelectedLine() {
				if (this.floorTileStatus) {
					uni.$u.toast('正在计算地砖，不可操作!');
					return;
				}
				if (this.selectedLine) {
					const index = this.lines.indexOf(this.selectedLine);
					if (index !== -1) {
						this.lines.splice(index, 1);
						this.selectedLine = null;
						this.redrawCanvas();
					}
				}
			},
			toMaterimal(){
				uni.navigateTo({
					url:'/pages/materimal/index?id=' + this.id + '&&brandPartyId=' + this.brandPartyId   
				})
			},
			computationalMaterials() {

				uni.$u.http.get('/materials/getMaterialsByDxf', {
					params: {
						assignTaskId: this.id,
						pageSize: 100000,
						pageNumber: 1
					}
				}).then(res => {
					if (res) {
						if (this.brandPartyId == 2) {
							res.data.map(el => {
								if (el.classificationId == 360) {
									el.count = this.wallboardNum;
								} else if (el.classificationId == 361) {
									el.count = this.wallboardNum;
								} else if (el.classificationId == 369) {
									el.count = this.floorTileNum
								} else {
									el.count = 0;
								}
								this.RBLIST.push(el)
							})
						} else if (this.brandPartyId == 1) {

						}

						this.RBSHOW = true;
					}
				})

			},
			copySelectedLine() {
				if (this.floorTileStatus) {
					uni.$u.toast('正在计算地砖，不可操作!');
					return;
				}
				if (this.selectedLine) {
					const index = this.lines.indexOf(this.selectedLine);
					let data = JSON.parse(JSON.stringify(this.selectedLine));
					if (index !== -1) {

						if (data.type == 'horizontal') {
							data.startY = Decimal(this.selectedLine.startY).add(Decimal(50)).toNumber();
							data.endY = Decimal(this.selectedLine.endY).add(Decimal(50)).toNumber();

						} else {
							data.startX = Decimal(this.selectedLine.startX).add(Decimal(50)).toNumber();
							data.endX = Decimal(this.selectedLine.endX).add(Decimal(50)).toNumber();

						}
						this.lines.push(data)
					}

					this.redrawCanvas();
				}
			},
			colorConfirm(e) {
				console.log(e)
			},
			undoLine() {
				if (this.floorTileStatus) {
					uni.$u.toast('正在计算地砖，不可操作!');
					return;
				}
				if (this.lines.length > 0) {
					this.lines.pop();
					this.selectedLine = null;
					this.redrawCanvas();
				}
			},

			setLineType(type) {
				this.lineType = type;
			},
			addLine() {
				if (!this.lineLength) {
					uni.$u.toast('请输入长度!');
					return;
				}
				if (this.floorTileStatus) {
					uni.$u.toast('正在计算地砖，不可操作!');
					return;
				}
				const length = Number(this.lineLength);
				if (length <= 0) return;

				let startX = 100;
				let startY = 100;
				if (this.lines.length >= 1) {
					startX = this.lines[this.lines.length - 1].endX;
					startY = this.lines[this.lines.length - 1].endY
				}
				let endX, endY;

				if (this.lineType === 'horizontal') {
					endX = startX + length;
					endY = startY;
				} else {
					endX = startX;
					endY = startY + length;
				}


				this.lines.push({
					startX,
					startY,
					endX,
					endY,
					type: this.lineType,
					color: this.lineColor,
					width: this.lineWidth,
				});

				this.redrawCanvas();
			},
			handleMouseDown(event) {
				this.startX = event.touches[0].clientX;
				this.startY = event.touches[0].clientY;
				this.offsetX = this.left;
				this.offsetY = this.top;


				const query = uni.createSelectorQuery();
				query.select('#firstCanvas').boundingClientRect(info => {
					this.downRect = info;
					// #ifdef MP-WEIXIN
					const mouseX = event.touches[0].clientX - this.downRect.left;
					const mouseY = event.touches[0].clientY - this.downRect.top;
					//  #endif
					// #ifdef APP-PLUS
					const mouseX = event.touches[0].x - this.downRect.left;
					const mouseY = event.touches[0].y - this.downRect.top;
					//  #endif

					if (this.floorTileStatus) {
						this.gridArr.map((el, index) => {
							let maxX, maxY = 0;
							if (this.brandPartyId == 1) {
								maxX = Decimal(el.x).add(Decimal(122)).toNumber();
								maxY = Decimal(el.y).add(Decimal(300)).toNumber();
							} else if (this.brandPartyId == 2) {
								maxX = Decimal(el.x).add(Decimal(120)).toNumber();
								maxY = Decimal(el.y).add(Decimal(60)).toNumber();
							}

							if (mouseX.toFixed(0) >= el.x && mouseX.toFixed(0) <= maxX && mouseY.toFixed(
									0) >= el.y && mouseY.toFixed(0) <= maxY) {
								this.delGrid.push(this.gridArr[index]);
								this.gridArr.splice(index, 1);
								this.redrawCanvas();
							}
						})

					} else {

						for (let i = 0; i < this.lines.length; i++) {
							let line = this.lines[i];
							if (this.isNearPoint(mouseX, mouseY, line.startX, line.startY, this.snapDistance) ||
								this.isNearPoint(mouseX, mouseY, line.endX, line.endY, this.snapDistance) ||
								this.isNearLine(mouseX, mouseY, line)) {
								this.draggingLine = line;
								this.draggingOffsetX = mouseX - line.startX; // 记录鼠标和线起点的偏移
								this.draggingOffsetY = mouseY - line.startY;
								this.selectedLine = line;
								this.isDrawing = true;
								if (this.mode === 'translate') {

									this.draggingLine = line;
									this.draggingOffsetX = mouseX - line.startX;
									this.draggingOffsetY = mouseY - line.startY;
								} else if (this.mode === 'rotate') {

									if (this.isNearPoint(mouseX, mouseY, line.startX, line.startY, this
											.snapDistance)) {
										this.rotatingLine = line;
										this.rotatingPoint = {
											x: line.endX,
											y: line.endY
										};
									} else if (this.isNearPoint(mouseX, mouseY, line.endX, line.endY, this
											.snapDistance)) {
										this.rotatingLine = line;
										this.rotatingPoint = {
											x: line.startX,
											y: line.startY
										};
									}
								}
								break;
							}
						}
					}
				}).exec();


			},

			handleMouseMove(event) {

				if (event.touches.length == 1) {

					if (this.floorTileStatus) {
						// uni.$u.toast('正在计算地砖，不可操作!');
						return;
					}
					// #ifdef MP-WEIXIN
					if (!this.isDrawing) return;
					//  #endif

					const query = uni.createSelectorQuery();
					query.select('#firstCanvas').boundingClientRect(info => {
						this.moveRect = info;

						// #ifdef MP-WEIXIN
						const mouseX = event.touches[0].clientX - this.moveRect.left;
						const mouseY = event.touches[0].clientY - this.moveRect.top;
						//  #endif
						// #ifdef APP-PLUS
						const mouseX = event.touches[0].x.toFixed(2) - this.moveRect.left;
						const mouseY = event.touches[0].y.toFixed(2) - this.moveRect.top;
						//  #endif
						if (this.mode === 'translate' && this.draggingLine) {
							// 平移模式：移动线

							const dx = mouseX - this.draggingLine.startX - this.draggingOffsetX;
							const dy = mouseY - this.draggingLine.startY - this.draggingOffsetY;

							this.draggingLine.startX += dx;
							this.draggingLine.startY += dy;
							this.draggingLine.endX += dx;
							this.draggingLine.endY += dy;
							if (!(this.draggingLine.startX !== this.draggingLine.endX && this.draggingLine
									.startY !== this.draggingLine.endY)) {

								this.snapLine(this.draggingLine);
							}

						} else if (this.mode === 'rotate' && this.rotatingLine && this.rotatingPoint) {

							const dx = mouseX - this.rotatingPoint.x;
							const dy = mouseY - this.rotatingPoint.y;
							const angle = Math.atan2(dy, dx);

							const length = Math.sqrt((this.rotatingLine.endX - this.rotatingLine.startX) ** 2 + (
								this.rotatingLine.endY - this.rotatingLine.startY) ** 2);
							if (this.rotatingPoint.x === this.rotatingLine.startX && this.rotatingPoint.y === this
								.rotatingLine.startY) {
								this.rotatingLine.endX = this.rotatingPoint.x + length * Math.cos(angle);
								this.rotatingLine.endY = this.rotatingPoint.y + length * Math.sin(angle);
							} else {
								this.rotatingLine.startX = this.rotatingPoint.x + length * Math.cos(angle);
								this.rotatingLine.startY = this.rotatingPoint.y + length * Math.sin(angle);
							}
						}
					}).exec();
					this.redrawCanvas();
				} else {
					// #ifdef MP-WEIXIN

					const currentX = event.touches[0].clientX;
					const currentY = event.touches[0].clientY;
					//  #endif
					// #ifdef APP-PLUS
					const currentX = event.touches[0].x;
					const currentY = event.touches[0].y;
					//  #endif

					this.left = this.offsetX + (currentX - this.startX);
					this.top = this.offsetY + (currentY - this.startY);

				}
			},
			handleMouseUp() {
				this.isDrawing = false;
				this.draggingLine = null;
				this.rotatingLine = null;
				this.rotatingPoint = null;
			},
			handleMouseLeave() {
				this.handleMouseUp();
			},

			isNearPoint(x1, y1, x2, y2, threshold) {
				const distance = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
				return distance <= threshold;
			},

			isNearLine(x, y, line) {

				const {
					startX,
					startY,
					endX,
					endY
				} = line;


				const minX = Math.min(startX, endX);
				const maxX = Math.max(startX, endX);
				const minY = Math.min(startY, endY);
				const maxY = Math.max(startY, endY);
				if (x < minX - this.snapDistance || x > maxX + this.snapDistance ||
					y < minY - this.snapDistance || y > maxY + this.snapDistance) {
					return false;
				}

				const A = endY - startY;
				const B = startX - endX;
				const C = endX * startY - startX * endY;
				const distance = Math.abs(A * x + B * y + C) / Math.sqrt(A * A + B * B);

				return distance <= this.snapDistance;
			},
			snapLine(movingLine) {
				for (const otherLine of this.lines) {
					if (otherLine === movingLine) continue;

					const points = [{
							x: movingLine.startX,
							y: movingLine.startY,
							type: 'start'
						},
						{
							x: movingLine.endX,
							y: movingLine.endY,
							type: 'end'
						},
					];
					const otherPoints = [{
							x: otherLine.startX,
							y: otherLine.startY,
							type: 'start'
						},
						{
							x: otherLine.endX,
							y: otherLine.endY,
							type: 'end'
						},
					];

					for (const point of points) {
						for (const otherPoint of otherPoints) {
							if (this.isNearPoint(point.x, point.y, otherPoint.x, otherPoint.y, this.snapDistance)) {

								const dx = otherPoint.x - point.x;
								const dy = otherPoint.y - point.y;

								movingLine.startX += dx;
								movingLine.startY += dy;
								movingLine.endX += dx;
								movingLine.endY += dy;


								this.adjustForParallelOrPerpendicular(movingLine, otherLine);
								return;
							}
						}
					}
				}
			},

			adjustForParallelOrPerpendicular(movingLine, otherLine) {

				const slopeMoving = (movingLine.endY - movingLine.startY) / (movingLine.endX - movingLine.startX);
				const slopeOther = (otherLine.endY - otherLine.startY) / (otherLine.endX - otherLine.startX);

				const isMovingHorizontal = Math.abs(slopeMoving) < 0.1;
				const isMovingVertical = Math.abs(slopeMoving) > 1000;
				const isOtherHorizontal = Math.abs(slopeOther) < 0.1;
				const isOtherVertical = Math.abs(slopeOther) > 1000;


				if ((isMovingHorizontal && isOtherHorizontal) || (isMovingVertical && isOtherVertical)) {

					return;

				} else if ((isMovingHorizontal && isOtherVertical) || (isMovingVertical && isOtherHorizontal)) {

					return;
				} else if (Math.abs(slopeMoving - slopeOther) < 0.1) {

					return;
				} else if (Math.abs(slopeMoving * slopeOther + 1) < 0.1) {

					return;
				} else {

					if (movingLine.type === 'horizontal') {
						movingLine.endY = movingLine.startY;

					} else {
						movingLine.endX = movingLine.startX;
					}
				}
			},
			clearCanvas() {
				this.lines = [];
				this.gridArr = [];
				this.floorTileNum = 0;
				this.wallboardNum = 0;
				this.wallboardLength = 0;
				this.carbonCrystalPlateLength = 0;
				this.floorTileStatus = false;
				this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
				this.ctx.draw();
			},
			redrawCanvas() {

				this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
				this.ctx.strokeRect(0, 0, this.canvasWidth, this.canvasHeight);
				// this.ctx.strokeStyle = '#000';
				for (const line of this.lines) {
					if (line === this.selectedLine) {
						this.ctx.strokeStyle = app.globalData.defaultColor;
						this.ctx.lineWidth = line.width + 1;
					} else {
						// 未被选中时恢复原来的样式
						this.ctx.strokeStyle = line.color;
						this.ctx.lineWidth = line.width;
					}

					this.ctx.beginPath();

					this.ctx.moveTo(line.startX, line.startY);
					this.ctx.lineTo(line.endX, line.endY);
					this.ctx.stroke();
					this.ctx.closePath();
					if (this.showAnnotations) {
						this.drawAnnotation(line);
					}


				}

				this.ctx.draw(false);
				// this.ctx.scale(this.scale, this.scale);
			},

			drawAnnotation(line) {
				const midX = (line.startX + line.endX) / 2;
				const midY = (line.startY + line.endY) / 2;
				const length = Math.sqrt((line.endX - line.startX) ** 2 + (line.endY - line.startY) ** 2);


				this.ctx.fillStyle = 'black';
				this.ctx.font = '12px Arial';
				this.ctx.textAlign = 'center';
				this.ctx.textBaseline = 'middle';


				this.ctx.fillText(`${length.toFixed(2)}`, midX, midY);
			},

		printLineInfo() {
				if (!this.id) {
					uni.$u.toast('体验不支持生成CAD!')
					return;
				}
				
				
				uni.showModal({
					title: '提示',
					content:`室外铝塑板${this.floorTileNum}块，确定下单？`,
					success:  (res) => {
						if (res.confirm) {
							for (const line of this.lines) {
							
								const length = Math.sqrt((line.endX - line.startX) ** 2 + (line.endY - line.startY) ** 2);
								// console.log(`线段: 起点(${line.startX}, ${line.startY}), 终点(${line.endX}, ${line.endY}), 长度: ${length.toFixed(2)}`);
								this.lineArry.push({
									startX: line.startX,
									startY: line.startY,
									endX: line.endX,
									endY: line.endY,
									length: length.toFixed(2),
									type: line.type
								});
							}
							 
							let data = {
								assignTaskId: this.id,
								list: this.lineArry,
								flag: 4
							}
							uni.$u.http.post('/dxf/add', data).then(res => {
								if (res) {
									this.saveMaterimal();
								}else{
									uni.$u.toast('CAD保存失败，请联系管理员!')
								}
								this.load = false
							})
							
						} else if (res.cancel) {
							uni.$u.toast('用户取消下单!')
						}
					}
				});
		},
		saveMaterimal(){
			uni.$u.http.get('/materials/getMaterialsByDxf', {
				params: {
					assignTaskId: this.id,
					pageSize: 100000,
					pageNumber: 1,
				}
			}).then(res => {
				 if(this.brandPartyId== 1){
					 let materitalList = []
					
					 res.data.map(el=>{
						  if(el.classificationId == 275){
							 el.count = this.floorTileNum
							 materitalList.push(el);
						  }
					 })
					 let arr = [];
					 let totalPrice = 0;
					 materitalList.map(el => {
					 	if (el.count > 0) {
					 		totalPrice += Decimal(el.count).mul(Decimal(el.firstMaterialPrice)).toNumber();
					 		arr.push({
					 			'buyCount': el.count,
					 			'name': el.classificationName,
					 			'classificationId': el.classificationId,
					 			'salePrice': el.firstMaterialPrice
					 		})
					 	}
					 })
					 let data = {
					 	assignTaskId: this.id,
					 	list: arr,
					 	totalPrice: totalPrice,
					 	state: 1,
					 	flag:4
					 }
					 uni.$u.http.post('/materials/addScaleMaterialsRecords', data).then(res => {
					 	if (res) {
					 		uni.$u.toast('保存材料成功!');
							setTimeout(()=>{
								this.toMaterimal();
							},2000)
					 	}else{
					 		uni.$u.toast('创建订单失败,请联系管理员!');
					 	}
					 })
					 
					 
				 }
			})
		}

		},

	}
</script>
<style>
	page {
		background: linear-gradient(-90deg, #DCF3F5, #EBF4F5);
		height: 100vh;
		width: 100vw;
		overflow: hidden;
	}
</style>
<style lang="scss" scoped>
	.tabbar {
		width: 100vw;
		position: fixed;
		bottom: 0;
		left: 0;
		// padding: 20rpx;
		border-radius: 20rpx;
		// padding-bottom: 30rpx;
		// background: white;
		z-index: 100;
	}

	.icon {
		padding-left: 20rpx;
		display: flex;
		align-items: center;
		position: fixed;
		z-index: 10000000;
		background: white;
		width: 100vw;

		image {
			margin-left: 25rpx;
			width: 40rpx;
			height: 40rpx;

		}
	}
</style>